const websocket = require('ws')

const ws = new websocket.Server({//创建端口8000的webssocket服务
    port:8000
})

let clients = {}
let clientNum = 0

ws.on("connection",(client)=>{
    //监听，连接客户端

    //给每个连接的客户端创建一个名字
    client.name = ++clientNum
    clients[client.name] = client // 创建键值对  "1":client实例

    //用client实例监听四个常用事件 open，message，error，close

    //监听客户端message事件，拿到客户端发送来的消息
    client.on("message",(msg)=>{
        console.log("用户"+client.name+"说："+msg)
        broadcast(client,msg)
    })

    //监听客户端error事件，拿到客户端发来的错误
    client.on("error",(err)=>{
        if(err){
            console.log(err)
        }
    })    

    //监听客户端close事件也就是下线事件，
    client.on("close",()=>{
        broadcastQuite(client)
        console.log("用户"+client.name+"下线了！！！")
        delete clients[client.name] // 从容器中删除下线的客户端实例
    })
})

//广播方法
function broadcast(client,msg){
    for(let key in clients){
        clients[key].send("用户"+client.name+"说："+msg)
    }
}

//广播自己下线了
function broadcastQuite(client){
    for(let key in clients){
        clients[key].send("系统提示：用户"+client.name+"下线了！")
    }
}





